package cn.thornbird.orgsync.util;

import lombok.extern.slf4j.Slf4j;

import java.io.*;

@Slf4j
public class StreamUtil {

    public static void copyFile(File sourceFile, File destinationFile) throws IOException {
        InputStream inputStream = new BufferedInputStream(new FileInputStream(sourceFile));
        OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(destinationFile));
        writeOutputStream(inputStream, outputStream);
    }

    public static void writeOutputStream(InputStream inputStream, OutputStream outputStream) throws IOException {
        try {
            int bytesRead;
            byte[] buffer = new byte[1024];
            while ((bytesRead = inputStream.read(buffer, 0, 1024)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            log.error("error", e);
            throw e;
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                log.error("error", e);
            }
        }
    }

}
